<?php
// 版权所有 (C) 2025 尋鯨錄
// 保留所有权利。
// 博客：https://www.xunjinlu.fun/
// 如需二开请保留版权，谢谢。

header('Content-Type: application/json');

require_once 'config.php';

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'login':
        handleLogin();
        break;
    case 'logout':
        handleLogout();
        break;
    case 'status':
        handleStatus();
        break;
    default:
        echo json_encode(array('success' => false, 'error' => '无效的操作'));
        break;
}

function handleLogin() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(array('success' => false, 'error' => '无效的请求方法'));
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $password = $input['password'] ?? '';
    
    if (empty($password)) {
        echo json_encode(array('success' => false, 'error' => '请输入密码'));
        return;
    }
    
    $result = loginUser($password);
    echo json_encode($result);
}

function handleLogout() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(array('success' => false, 'error' => '无效的请求方法'));
        return;
    }
    
    $result = logoutUser();
    echo json_encode($result);
}

function handleStatus() {
    $status = getAuthStatus();
    echo json_encode(array('success' => true, 'data' => $status));
}
?> 